package ca.unbc.cpsc672.fuzzy.function;

public class Piecewise extends MembershipFunction {
	private static final String P1 = "P1";
	private static final String P2 = "P2";
	private static final String P3 = "P3";
	private static final String P4 = "P4";

	public Piecewise(String label, double[] paras) {
		super(label);
		addParamenter(P1, paras[0]);
		addParamenter(P2, paras[1]);
		addParamenter(P3, paras[2]);
		addParamenter(P4, paras[3]);
	}

	@Override
	public double getCenter() {
		return (getParamenter(P2) + getParamenter(P3)) / 2;
	}

	// LaTeX code
	// f(x)=\begin{cases}
	// & 0\text{ if } x < p_{}1 , x> p_{}4 \\
	// & mx+n\text{ if } p1 \leqslant x < p_{}2 \\
	// & 1\text{ if } p_{}2 \leqslant x \leqslant p_{}3 \\
	// & m{}'x+n{}'\text{ if } p_{}3 < x < p_{}4
	// \end{cases}
	@Override
	protected String getImageName() {
		return "Piecewise.gif";
	}

	@Override
	protected double calcFunction(double x) {
		double p1 = getParamenter(P1);
		double p2 = getParamenter(P2);
		double p3 = getParamenter(P3);
		double p4 = getParamenter(P4);
		if (x > p1 && x < p2) {
			double m = 1 / (p2 - p1);
			double n = -m * p1;
			return m * x + n;
		} else if (x >= p2 && x <= p3) {
			return 1;
		} else if (x > p3 && x < p4) {
			double m = 1 / (p3 - p4);
			double n = -m * p4;
			return m * x + n;
		} else
			return 0;
	}
}
